<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="60%" title="文档版本历史">
    <div class="version-history-container">
      <div class="version-info">
        <p>版本号格式说明：YYYYMMDD.HHMMSS（年月日.时分秒）</p>
      </div>
      <el-table :data="versionHistory" style="width: 100%" max-height="400">
        <el-table-column prop="version" label="版本" width="150" />
        <el-table-column prop="createDate" label="创建时间" width="180">
          <template #default="scope">
            {{ useDateFormat(scope.row.createDate, "YYYY-MM-DD HH:mm:ss").value }}
          </template>
        </el-table-column>
        <el-table-column prop="createUser" label="创建人" width="120">
          <template #default="scope">
            {{ formatUserName(scope.row.createUser) }}
          </template>
        </el-table-column>
        <el-table-column prop="note" label="备注" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="viewVersion(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="restoreVersion(scope.row)">恢复</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="version-content" v-if="selectedVersion">
        <h3>版本内容预览：{{ selectedVersion.version }}</h3>
        <div class="markdown-body" v-html="selectedVersion.content"></div>
      </div>
    </div>

    <template #footer>
      <el-button @click="drawerVisible = false">关闭</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="VersionHistoryDrawer">
import { ref, onMounted } from "vue";
import { useDateFormat } from "@vueuse/core";
import { ElMessage, ElMessageBox } from "element-plus";
import apiService from "@/api/services/apiService";
import { useDataStore } from "@/stores/modules/data";
import type { ShareDocVersion } from "./types/document";

const drawerVisible = ref(false);
const versionHistory = ref<ShareDocVersion[]>([]);
const selectedVersion = ref<ShareDocVersion | null>(null);
const catalogId = ref<string>("");
const dataStore = useDataStore();

// 在组件挂载时加载用户列表
onMounted(async () => {
  if (dataStore.userList.length === 0) {
    await dataStore.findUserList();
  }
});

interface DrawerProps {
  catalogId: string;
}

// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  catalogId.value = params.catalogId;
  drawerVisible.value = true;
  await loadVersionHistory();
};

// 加载版本历史
const loadVersionHistory = async () => {
  try {
    const { data } = await apiService.find<ShareDocVersion[]>(
      "shareDocVersions",
      { catalogId: catalogId.value },
      { sort: { createDate: -1 } }
    );
    versionHistory.value = data;
    // 清空之前选中的版本
    selectedVersion.value = null;
  } catch (error) {
    console.error("加载版本历史失败:", error);
    ElMessage.error("加载版本历史失败");
  }
};

// 查看版本
const viewVersion = async (version: ShareDocVersion) => {
  selectedVersion.value = version;
};

// 恢复版本
const restoreVersion = async (version: ShareDocVersion) => {
  ElMessageBox.confirm(`确定要恢复到版本 ${version.version} 吗？这将覆盖当前文档内容。`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        // 更新当前文档内容
        await apiService.updateById("sharedocs", { _id: version.catalogId, content: version.content });
        ElMessage.success("版本恢复成功");
        // 关闭抽屉
        drawerVisible.value = false;
        // 触发事件通知父组件刷新内容
        emit("versionRestored");
      } catch (error) {
        console.error("版本恢复失败:", error);
        ElMessage.error("版本恢复失败");
      }
    })
    .catch(() => {
      // 用户取消操作
    });
};

// 用户名称转换
const formatUserName = (userId: string | undefined) => {
  // 如果没有用户ID，返回默认值
  if (!userId) {
    return "未知用户";
  }

  // 如果用户列表为空，返回用户ID
  if (!dataStore.userList || dataStore.userList.length === 0) {
    return userId;
  }

  // 查找用户
  const user = dataStore.userList.find(item => item._id === userId);
  if (user) {
    return user.userName || "未知用户";
  } else {
    return "未知用户";
  }
};

const emit = defineEmits<{
  (e: "versionRestored"): void;
}>();

defineExpose({
  acceptParams
});
</script>

<style scoped lang="scss">
.version-history-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  .version-info {
    padding: 10px;
    margin-bottom: 10px;
    background-color: var(--el-fill-color-light);
    border-radius: 4px;
    p {
      margin: 0;
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }
}
.version-content {
  flex: 1;
  padding: 10px;
  margin-top: 20px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
.markdown-body {
  padding: 10px;

  // 富文本内容样式
  :deep(img) {
    max-width: 100%;
  }
  :deep(pre) {
    padding: 10px;
    overflow: auto;
    background-color: var(--el-fill-color-light);
    border-radius: 4px;
  }
}
</style>
